package com.example.myyunpan.service.impl;

import com.example.myyunpan.component.RedisComponent;
import com.example.myyunpan.entity.config.AppConfig;
import com.example.myyunpan.entity.constants.Constants;
import com.example.myyunpan.entity.domain.UserInfo;
import com.example.myyunpan.entity.dto.SysSettingsDto;
import com.example.myyunpan.mapper.UserInfoMapper;
import com.example.myyunpan.service.EmailCodeService;
import com.example.myyunpan.utils.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myyunpan.entity.domain.EmailCode;
import com.example.myyunpan.mapper.EmailCodeMapper;

import javax.mail.internet.MimeMessage;


/**
* @author 111
* @description 针对表【email_code(邮箱验证码)】的数据库操作Service实现
* @createDate 2024-10-23 11:41:27
*/
@Service
public class EmailCodeServiceImpl extends ServiceImpl<EmailCodeMapper, EmailCode> implements EmailCodeService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private EmailCodeMapper emailCodeMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * @return
     * @param @param null
     * @author znk
     * @date 2024/10/25 18:27
     * 作为整个项目中，项目信息的获取，其中的属性在配置文件中获取
     */
    @Autowired
    private AppConfig appConfig;

    @Autowired
    private RedisComponent redisComponent;


    private void sendEmailCode(String email, String randomNumber){
        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(appConfig.getSendUserName());
            mimeMessageHelper.setTo(email);
//            TODO 作为前端响应邮箱实体类
            SysSettingsDto sysSettings = redisComponent.getSysSettings(randomNumber);
            mimeMessageHelper.setSubject(sysSettings.getRegisterEmailTitle());
            mimeMessageHelper.setText(String.format(sysSettings.getRegisterEmailContent(),randomNumber),true);
            mimeMessageHelper.setSentDate(new java.util.Date());
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            log.error("发送邮件失败",e);
            throw new RuntimeException("发送邮件失败");
        }

    }

    @Override
    public void sendEmailCode(String email, Integer type) {
        if(type == Constants.ZERO){
            UserInfo userInfo = userInfoMapper.selectByEmailUserInfo(email);
            if(userInfo != null){
                throw new RuntimeException("邮箱已经存在!");
            }
        }
        String randomNumber = StringTools.getRandomNumber(Constants.LENGTH_5);
//        TODO 发送验证码
        sendEmailCode(email, randomNumber);

//        将之前的验证码值为无效
        emailCodeMapper.disableEmailCode(email);
        EmailCode emailCode = new EmailCode();
        emailCode.setEmail(email);
        emailCode.setCode(randomNumber);
        emailCode.setCreateTime(new java.util.Date());
        emailCode.setStatus(Constants.ZERO);
        emailCodeMapper.insert(emailCode);
    }

    @Override
    public void checkEmailCode(String email, String code) {
        EmailCode emailCode=emailCodeMapper.selectByEmailAndCode(email,code);
        if(emailCode == null){
            throw new RuntimeException("邮箱验证码不正确!");
        }
        if(emailCode.getStatus() == Constants.ONE || System.currentTimeMillis()- emailCode.getCreateTime().getTime()
                > Constants.LENGTH_15 * 60 * 1000){
            throw new RuntimeException("邮箱验证码已失效!");
        }
//        校验邮箱验证码
        emailCodeMapper.disableEmailCode(email);
    }

}
